import React, { Component } from 'react'
import { connect } from 'react-redux'
import axios from 'axios'
import { Button } from 'antd-mobile'
import { withRouter } from 'react-router-dom'

export class Classify extends Component {
    pushDetail = (item) => {
        this.props.history.push({
            pathname: '/detail',
            state: {
                item
            }
        })
    }
    render() {
        const { initList, addItem } = this.props
        return (
            <div>
                <ul>
                    {
                        initList.map((item, index) => {
                            return <li className="oli" key={index}>
                                <div className="left">
                                    <img onClick = { () => {
                                        this.pushDetail(item)
                                    }} src={item.img} alt="" />
                                </div>
                                <div className="right">
                                    <h3>
                                        {item.title}
                                    </h3>
                                    <h4>
                                        {item.price}
                                    </h4>
                                    <Button onClick = {() => {
                                        addItem(item)
                                    }} type="primary">添加</Button>
                                </div>
                            </li>
                        })
                    }
                </ul>
            </div>
        )
    }
    componentDidMount() {
        this.props.init()
    }
}

const mapStateToProps = (state) => ({
    initList: state.initList
})

const mapDispatchToProps = (dispatch) => {
    return {
        init() {
            // 初始赋值
            dispatch((next) => {
                axios.get("/getList").then(res => {
                    //  dispatch
                    //  next
                    next({ type: "SET_LIST", res: res.data.data })
                    console.log(res.data.data)
                })
            })
        },
        addItem(item) {
            dispatch({ type: "ADD_ITEM", item })
        }
    }
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Classify))
